package de.preisrobot.persistence.dao;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class AbstractDao<T> implements Dao<T> {
    
    private static final Logger LOG = LoggerFactory.getLogger(AbstractDao.class);  

    @PersistenceContext
    protected EntityManager entityManager;

    public void persist(T transientInstance) {
        try {
            entityManager.persist(transientInstance);
        } catch (RuntimeException re) {
            LOG.error("persist failed", re);
            throw re;
        }
    }

    public void remove(T persistentInstance) {
        try {
            T object2delete = merge (persistentInstance);
            entityManager.remove(object2delete);
        } catch (RuntimeException re) {
            LOG.error("remove failed", re);
            throw re;
        }
    }

    public T merge(T detachedInstance) {
        try {
            T result = entityManager.merge(detachedInstance);
            return result;
        } catch (RuntimeException re) {
            LOG.error("merge failed", re);
            throw re;
        }
    }
    
    public <U> U getReference(Class<U> clazz, Object id) {
    	return entityManager.getReference(clazz, id);
    }
    
    protected String getStringId(String seqName) {
        Query query = entityManager.createNativeQuery("select "+seqName+".nextval from dual");
        Number id = (Number) query.getSingleResult();
        return id.toString();
    }
    
    @Override
	public void flush(){
		entityManager.flush();
	
	}
    
    @Override
    public void refresh(T entity){
    	entityManager.refresh(entity);
    }
}
